<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <div class="max-w-4xl mx-auto">
      <!-- 页面标题 -->
      <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-900 mb-2">案件签约</h1>
        <p class="text-gray-600">完善签约信息并上传合同文件</p>
      </div>

      <!-- 返回按钮 -->
      <div class="mb-6">
        <button @click="goBack" class="flex items-center text-blue-600 hover:text-blue-800">
          <i class="fas fa-arrow-left mr-2"></i>返回案件创建
        </button>
      </div>

      <!-- 基本信息回显 -->
      <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4 text-gray-800 flex items-center">
          <i class="fas fa-info-circle text-blue-600 mr-2"></i>案件基本信息
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">案件编号</label>
            <p class="text-gray-900">{{ caseInfo.caseNumber || '自动生成' }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">案件类型</label>
            <p class="text-gray-900">{{ caseInfo.caseType || '未设置' }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">客户姓名</label>
            <p class="text-gray-900">{{ caseInfo.clientName || '未填写' }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">联系电话</label>
            <p class="text-gray-900">{{ caseInfo.clientPhone || '未填写' }}</p>
          </div>
        </div>
      </div>

      <!-- 当事人信息回显 -->
      <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4 text-gray-800 flex items-center">
          <i class="fas fa-users text-blue-600 mr-2"></i>当事人信息
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">身份证号</label>
            <p class="text-gray-900">{{ caseInfo.clientIdCard || '未填写' }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">地址</label>
            <p class="text-gray-900">{{ caseInfo.clientAddress || '未填写' }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">年龄</label>
            <p class="text-gray-900">{{ caseInfo.clientAge || '未填写' }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">性别</label>
            <p class="text-gray-900">{{ caseInfo.clientGender || '未填写' }}</p>
          </div>
        </div>
      </div>

      <!-- 签约信息 -->
      <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4 text-gray-800 flex items-center">
          <i class="fas fa-file-signature text-blue-600 mr-2"></i>签约信息
        </h2>
        <div class="space-y-4">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">签约日期</label>
              <input 
                type="date" 
                v-model="contractForm.signDate"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">合同金额</label>
              <input 
                type="number" 
                v-model="contractForm.contractAmount"
                placeholder="请输入合同金额"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
            </div>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">付款方式</label>
            <select 
              v-model="contractForm.paymentMethod"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="">请选择付款方式</option>
              <option value="lump_sum">一次性付款</option>
              <option value="installment">分期付款</option>
              <option value="success_fee">风险代理</option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">合同备注</label>
            <textarea 
              v-model="contractForm.contractNotes"
              rows="3"
              placeholder="请输入合同相关备注..."
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            ></textarea>
          </div>
        </div>
      </div>

      <!-- 合同上传 -->
      <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4 text-gray-800 flex items-center">
          <i class="fas fa-upload text-blue-600 mr-2"></i>合同上传
        </h2>
        
        <div class="space-y-4">
          <!-- 委托代理合同 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">委托代理合同 *</label>
            <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors">
              <input 
                type="file" 
                @change="handleContractUpload($event, 'agency')"
                accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                class="hidden"
                ref="agencyContractInput"
              >
              <div v-if="!uploadedContracts.agency.length" class="cursor-pointer" @click="$refs.agencyContractInput.click()">
                <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                <p class="text-gray-600">点击上传委托代理合同</p>
                <p class="text-sm text-gray-500 mt-1">支持PDF、Word、图片格式，大小不超过10MB</p>
              </div>
              <div v-else>
                <div v-for="(file, index) in uploadedContracts.agency" :key="index" 
                     class="flex items-center justify-between bg-gray-50 p-3 rounded-lg mb-2">
                  <div class="flex items-center">
                    <i class="fas fa-file-alt text-blue-600 mr-2"></i>
                    <span class="text-sm text-gray-700">{{ file.name }}</span>
                  </div>
                  <button @click="removeContractFile('agency', index)" class="text-red-600 hover:text-red-800">
                    <i class="fas fa-times"></i>
                  </button>
                </div>
                <button @click="$refs.agencyContractInput.click()" 
                        class="text-blue-600 hover:text-blue-800 text-sm">
                  + 添加更多文件
                </button>
              </div>
            </div>
          </div>

          <!-- 风险代理合同 -->
          <div v-if="contractForm.paymentMethod === 'success_fee'">
            <label class="block text-sm font-medium text-gray-700 mb-2">风险代理合同</label>
            <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors">
              <input 
                type="file" 
                @change="handleContractUpload($event, 'risk')"
                accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                class="hidden"
                ref="riskContractInput"
              >
              <div v-if="!uploadedContracts.risk.length" class="cursor-pointer" @click="$refs.riskContractInput.click()">
                <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                <p class="text-gray-600">点击上传风险代理合同</p>
                <p class="text-sm text-gray-500 mt-1">支持PDF、Word、图片格式，大小不超过10MB</p>
              </div>
              <div v-else>
                <div v-for="(file, index) in uploadedContracts.risk" :key="index" 
                     class="flex items-center justify-between bg-gray-50 p-3 rounded-lg mb-2">
                  <div class="flex items-center">
                    <i class="fas fa-file-alt text-blue-600 mr-2"></i>
                    <span class="text-sm text-gray-700">{{ file.name }}</span>
                  </div>
                  <button @click="removeContractFile('risk', index)" class="text-red-600 hover:text-red-800">
                    <i class="fas fa-times"></i>
                  </button>
                </div>
                <button @click="$refs.riskContractInput.click()" 
                        class="text-blue-600 hover:text-blue-800 text-sm">
                  + 添加更多文件
                </button>
              </div>
            </div>
          </div>

          <!-- 其他合同文件 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">其他合同文件</label>
            <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors">
              <input 
                type="file" 
                @change="handleContractUpload($event, 'other')"
                accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                class="hidden"
                ref="otherContractInput"
                multiple
              >
              <div v-if="!uploadedContracts.other.length" class="cursor-pointer" @click="$refs.otherContractInput.click()">
                <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                <p class="text-gray-600">点击上传其他合同文件</p>
                <p class="text-sm text-gray-500 mt-1">支持PDF、Word、图片格式，大小不超过10MB</p>
              </div>
              <div v-else>
                <div v-for="(file, index) in uploadedContracts.other" :key="index" 
                     class="flex items-center justify-between bg-gray-50 p-3 rounded-lg mb-2">
                  <div class="flex items-center">
                    <i class="fas fa-file-alt text-blue-600 mr-2"></i>
                    <span class="text-sm text-gray-700">{{ file.name }}</span>
                  </div>
                  <button @click="removeContractFile('other', index)" class="text-red-600 hover:text-red-800">
                    <i class="fas fa-times"></i>
                  </button>
                </div>
                <button @click="$refs.otherContractInput.click()" 
                        class="text-blue-600 hover:text-blue-800 text-sm">
                  + 添加更多文件
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-end space-x-4">
        <button @click="goBack" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50">
          取消
        </button>
        <button @click="saveContract" class="px-6 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700">
          <i class="fas fa-save mr-2"></i>保存签约
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

export default {
  name: 'ContractSigning',
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // 案件信息（从路由参数获取）
    const caseInfo = ref({})
    
    // 签约表单
    const contractForm = reactive({
      signDate: new Date().toISOString().split('T')[0],
      contractAmount: '',
      paymentMethod: '',
      contractNotes: ''
    })
    
    // 上传的合同文件
    const uploadedContracts = reactive({
      agency: [], // 委托代理合同
      risk: [], // 风险代理合同
      other: [] // 其他合同文件
    })
    
    // 页面加载时获取传递的案件信息
    onMounted(() => {
      if (route.query.caseData) {
        try {
          caseInfo.value = JSON.parse(decodeURIComponent(route.query.caseData))
        } catch (error) {
          console.error('解析案件数据失败:', error)
        }
      }
    })
    
    // 返回案件创建页面
    const goBack = () => {
      router.push('/marketing/case/create')
    }
    
    // 处理合同文件上传
    const handleContractUpload = (event, type) => {
      const files = Array.from(event.target.files)
      files.forEach(file => {
        if (file.size > 10 * 1024 * 1024) {
          alert('文件大小不能超过10MB')
          return
        }
        uploadedContracts[type].push({
          name: file.name,
          size: file.size,
          file: file
        })
      })
      event.target.value = '' // 清空input，允许重复选择同一文件
    }
    
    // 删除合同文件
    const removeContractFile = (type, index) => {
      uploadedContracts[type].splice(index, 1)
    }
    
    // 保存签约信息
    const saveContract = async () => {
      // 验证必填字段
      if (!contractForm.signDate) {
        alert('请选择签约日期')
        return
      }
      
      if (!contractForm.contractAmount) {
        alert('请输入合同金额')
        return
      }
      
      if (!contractForm.paymentMethod) {
        alert('请选择付款方式')
        return
      }
      
      if (!uploadedContracts.agency.length) {
        alert('请上传委托代理合同')
        return
      }
      
      try {
        // 这里应该调用API保存签约信息
        const contractData = {
          caseInfo: caseInfo.value,
          contractForm: contractForm,
          uploadedContracts: uploadedContracts
        }
        
        console.log('保存签约数据:', contractData)
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        alert('签约信息保存成功！')
        router.push('/marketing/cases')
      } catch (error) {
        console.error('保存签约信息失败:', error)
        alert('保存签约信息失败')
      }
    }
    
    return {
      caseInfo,
      contractForm,
      uploadedContracts,
      goBack,
      handleContractUpload,
      removeContractFile,
      saveContract
    }
  }
}
</script>

<style scoped>
.upload-area {
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #3b82f6;
  background-color: #f8fafc;
}
</style>
